#include "../include/tcp_server.h"
#include <cassert>

namespace net {

TcpServer::TcpServer(int port)
    : _port(port),
      _nextId(0),
      _timeout(0),
      _enableInactiveRelease(false),
      _acceptor(&_baseloop, port),
      _pool(&_baseloop) 
{
    // 设置连接接受回调
    _acceptor.setAcceptCallback(std::bind(&TcpServer::newConnection, this, std::placeholders::_1));
    // 启动监听
    _acceptor.listen();
}

void TcpServer::setThreadCount(int count) 
{
    _pool.setThreadCount(count);
}

void TcpServer::setConnectedCallback(const std::function<void(const PtrConnection&)>& cb) 
{
    _connectedCallback = cb;
}

void TcpServer::setMessageCallback(const std::function<void(const PtrConnection&, Buffer*)>& cb) 
{
    _messageCallback = cb;
}

void TcpServer::setClosedCallback(const std::function<void(const PtrConnection&)>& cb) 
{
    _closedCallback = cb;
}

void TcpServer::setAnyEventCallback(const std::function<void(const PtrConnection&)>& cb) 
{
    _eventCallback = cb;
}

void TcpServer::enableInactiveRelease(int timeout) 
{
    _timeout = timeout;
    _enableInactiveRelease = true;
}

void TcpServer::runAfter(const Functor& task, int delay) 
{
    _baseloop.runInLoop(std::bind(&TcpServer::runAfterInLoop, this, task, delay));
}

void TcpServer::start() 
{
    // 创建线程池
    _pool.create();
    // 启动主事件循环（阻塞当前线程）
    _baseloop.start();
}

// 内部方法实现
void TcpServer::runAfterInLoop(const Functor& task, int delay) 
{
    _nextId++;
    _baseloop.timerAdd(_nextId, delay, task);
}

void TcpServer::newConnection(int fd) 
{
    // 生成唯一连接ID
    _nextId++;
    // 创建新连接对象（选择一个从属EventLoop）
    PtrConnection conn(new Connection(_pool.nextLoop(), _nextId, fd));
    
    // 设置回调函数
    conn->setMessageCallback(_messageCallback);
    conn->setClosedCallback(_closedCallback);
    conn->setConnectedCallback(_connectedCallback);
    conn->setAnyEventCallback(_eventCallback);
    conn->setSrvClosedCallback(std::bind(&TcpServer::removeConnection, this, std::placeholders::_1));

    // 启用非活跃连接释放（如果配置）
    if (_enableInactiveRelease) 
    {
        conn->enableInactiveRelease(_timeout);
    }

    // 初始化连接
    conn->established();
    // 将连接添加到管理器
    _conns.insert(std::make_pair(_nextId, conn));
}

void TcpServer::removeConnection(const PtrConnection& conn) 
{
    // 在主EventLoop线程中移除连接
    _baseloop.runInLoop(std::bind(&TcpServer::removeConnectionInLoop, this, conn));
}

void TcpServer::removeConnectionInLoop(const PtrConnection& conn) 
{
    uint64_t id = conn->id();
    auto it = _conns.find(id);
    if (it != _conns.end()) 
    {
        _conns.erase(it);
        LOG_DEBUG("Connection [id=%lu] removed from server", id);
    }
}

} // namespace net